<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>个人信息</title>
    <style>
        .container {
            width: 800px;
            margin: 50px auto;
            padding: 20px;
        }
        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 30px;
            padding-bottom: 10px;
            border-bottom: 1px solid #ddd;
        }
        .profile-form {
            margin-top: 20px;
            padding: 20px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        .form-group {
            margin-bottom: 20px;
        }
        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: bold;
            color: #333;
        }
        .form-group input {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
        }
        .form-group input:focus {
            outline: none;
            border-color: #4CAF50;
        }
        .avatar-group {
            text-align: center;
            margin-bottom: 30px;
        }
        .avatar-preview {
            width: 120px;
            height: 120px;
            border-radius: 50%;
            object-fit: cover;
            margin-bottom: 10px;
            border: 2px solid #ddd;
        }
        .avatar-upload {
            display: none;
        }
        .upload-btn {
            background-color: #4CAF50;
            color: white;
            padding: 8px 15px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
        .btn {
            padding: 8px 15px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
        .save-btn {
            background-color: #4CAF50;
            color: white;
        }
        .back-btn {
            background-color: #666;
            color: white;
        }
        .btn:hover {
            opacity: 0.9;
        }
        .error-message {
            color: red;
            margin-top: 10px;
            display: none;
        }
        .email-group {
            display: flex;
            gap: 10px;
        }
        .email-group input {
            flex: 1;
        }
        .send-code-btn {
            background-color: #4CAF50;
            color: white;
            white-space: nowrap;
        }
        .code-input-group {
            margin-top: 10px;
        }
        .code-input-group input {
            width: 100%;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h2>个人信息</h2>
            <button class="btn back-btn" onclick="goBack()">返回</button>
        </div>
        <div class="profile-form">
            <div class="avatar-group">
                <img id="avatarPreview" class="avatar-preview" src="" alt="头像预览">
                <input type="file" id="avatar" class="avatar-upload" accept="image/*" onchange="previewAvatar(event)">
                <button class="upload-btn" onclick="document.getElementById('avatar').click()">更换头像</button>
            </div>
            <div class="form-group">
                <label for="username">用户名</label>
                <input type="text" id="username" name="username" readonly>
            </div>
            <div class="form-group">
                <label for="nickname">昵称</label>
                <input type="text" id="nickname" name="nickname" placeholder="请输入昵称">
            </div>
            <div class="form-group">
                <label for="mobile">手机号</label>
                <input type="text" id="mobile" name="mobile" placeholder="请输入手机号">
            </div>
            <div class="form-group">
                <label for="email">邮箱</label>
                <div class="email-group">
                    <input type="email" id="email" name="email" placeholder="请输入邮箱" onchange="handleEmailChange()">
                    <button class="btn send-code-btn" onclick="sendCode()">发送验证码</button>
                </div>
                <div id="codeInputGroup" class="code-input-group" style="display: none;">
                    <input type="text" id="code" name="code" placeholder="请输入验证码">
                </div>
            </div>
            <button class="btn save-btn" onclick="updateProfile()">保存</button>
            <div id="errorMessage" class="error-message"></div>
        </div>
    </div>

    <script>
        // 检查登录状态
        function checkLogin() {
            const user = JSON.parse(localStorage.getItem('user'));
            console.log('User from localStorage:', user);
            if (!user) {
                window.location.href = '/login.html';
                return null;
            }
            return user;
        }

        // 加载用户信息
        function loadUserInfo() {
            const user = checkLogin();
            console.log('Loading user info:', user);
            if (user) {
                document.getElementById('username').value = user.username || '';
                document.getElementById('nickname').value = user.nickname || '';
                document.getElementById('mobile').value = user.mobile || '';
                document.getElementById('email').value = user.email || '';
                originalEmail = user.email || ''; // 保存原始邮箱
                if (user.avatar) {
                    document.getElementById('avatarPreview').src = user.avatar;
                } else {
                    document.getElementById('avatarPreview').src = '/images/default-avatar.png';
                }
            } else {
                console.log('No user info found');
            }
        }

        // 预览头像
        function previewAvatar(event) {
            const file = event.target.files[0];
            if (file) {
                const reader = new FileReader();
                reader.onload = function(e) {
                    document.getElementById('avatarPreview').src = e.target.result;
                };
                reader.readAsDataURL(file);
            }
        }

        // 显示错误信息
        function showError(message) {
            const errorDiv = document.getElementById('errorMessage');
            errorDiv.textContent = message;
            errorDiv.style.display = 'block';
        }

        // 处理邮箱变更
        function handleEmailChange() {
            const newEmail = document.getElementById('email').value;
            if (newEmail !== originalEmail) {
                document.getElementById('codeInputGroup').style.display = 'block';
                emailVerified = false;
            } else {
                document.getElementById('codeInputGroup').style.display = 'none';
                emailVerified = true;
            }
        }

        // 发送验证码
        function sendCode() {
            const email = document.getElementById('email').value;
            if (!email) {
                showError('请输入邮箱地址');
                return;
            }
            
            // 验证邮箱格式
            const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
            if (!emailRegex.test(email)) {
                showError('请输入正确的邮箱地址');
                return;
            }
            
            fetch('/user/sendEmailCode', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'token': localStorage.getItem('token')
                },
                body: JSON.stringify({ email: email })
            })
            .then(response => response.json())
            .then(result => {
                if (result.code === 200) {
                    alert('验证码已发送到您的邮箱');
                } else {
                    showError(result.msg || '验证码发送失败');
                }
            })
            .catch(error => {
                showError('服务器错误，请稍后重试');
                console.error('Error:', error);
            });
        }

        // 更新用户信息
        async function updateProfile() {
            try {
                const nickname = document.getElementById('nickname').value;
                const mobile = document.getElementById('mobile').value;
                const email = document.getElementById('email').value;
                let avatar = document.getElementById('avatarPreview').src;

                // 如果头像是base64格式，则先上传
                if (avatar.startsWith('data:image')) {
                    // 将base64转换为文件
                    const response = await fetch(avatar);
                    const blob = await response.blob();
                    const file = new File([blob], "avatar.jpg", { type: "image/jpeg" });

                    // 创建FormData
                    const formData = new FormData();
                    formData.append('file', file);

                    // 上传头像
                    const uploadResult = await fetch('/user/uploadAvatar', {
                        method: 'POST',
                        headers: {
                            'token': localStorage.getItem('token')
                        },
                        body: formData
                    }).then(res => res.json());

                    if (uploadResult.code === 200) {
                        avatar = uploadResult.data;
                    } else {
                        showError('头像上传失败');
                        return;
                    }
                }

                // 更新用户信息前验证
                if (email !== originalEmail && !emailVerified) {
                    const code = document.getElementById('code').value;
                    if (!code) {
                        showError('请输入验证码');
                        return;
                    }
                    
                    try {
                        const verifyResult = await fetch('/user/verifyEmailCode', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                                'token': localStorage.getItem('token')
                            },
                            body: JSON.stringify({
                                email: email,
                                code: code
                            })
                        }).then(res => res.json());

                        if (verifyResult.code !== 200) {
                            showError('验证码错误');
                            return;
                        }
                        emailVerified = true;
                    } catch (error) {
                        showError('验证失败，请重试');
                        return;
                    }
                }

                // 更新用户信息
                const updateResult = await fetch('/user/update', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'token': localStorage.getItem('token')
                    },
                    body: JSON.stringify({
                        nickname: nickname,
                        mobile: mobile,
                        email: email,
                        avatar: avatar
                    })
                }).then(res => res.json());

                if (updateResult.code === 200) {
                    // 更新本地存储的用户信息
                    const user = JSON.parse(localStorage.getItem('user'));
                    user.nickname = nickname;
                    user.mobile = mobile;
                    user.email = email;
                    user.avatar = avatar;
                    localStorage.setItem('user', JSON.stringify(user));
                    console.log('Updated user info:', user);
                    alert('更新成功');
                    goBack();
                } else {
                    showError(updateResult.msg || '更新失败');
                }
            } catch (error) {
                showError('服务器错误，请稍后重试');
                console.error('Error:', error);
            }
        }

        // 返回上一页
        function goBack() {
            window.location.href = '/index.html';
        }

        // 页面加载时加载用户信息
        window.onload = function() {
            loadUserInfo();
        }
    </script>
</body>
</html> 